package com.flute.icrawler.app.processor.extractor.special;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;

import com.flute.icrawler.htmlparser.impl.BasicHtmlParser;
import com.flute.icrawler.htmlparser.util.DOMUtil;
import com.flute.icrawler.framework.framework.CrawlUrl;

/**
 * 获取 56 视频评论页面url
 * 
 */
public class FiveSixCommentAlgo implements IExtractorBelongingsAlgo {
	private static Logger logger = Logger.getLogger(FiveSixCommentAlgo.class);
	private static final String COMMENTURL = "http://comment.56.com/new/review/load.utf8.php?a=flv&pct=1&user_id=hermes2010&pageRows=20&id=";

	/**
	 * 评论内容页面url
	 * 
	 * @param url
	 * @return
	 */
	public String[] extractor(CrawlUrl url) {
		String id = this.getVedioID(url.getUrl());
		int maxpage = this.getMaxpage(id);
		String[] array = new String[maxpage];
		for (int i = 1; i <= maxpage; i++) {
			array[i - 1] = COMMENTURL + id + "&page=" + i;
		}
		return array;
	}

	/**
	 * 取得评论的最大页数
	 * 
	 * @param url
	 * @return
	 */
	private int getMaxpage(String id) {
		try {
			Document doc = new BasicHtmlParser().getDocument(COMMENTURL + id + "&page=1", BasicHtmlParser.HTML_STATIC);
			String content = DOMUtil.getHtml(doc);
			Pattern p = Pattern.compile("var\\s+_XYP\\s*?=\\s*?\\{\\\"count\\\":\\\"(.+?)\\\",\\\"data\\\":\\[");
			Matcher m = p.matcher(content);
			if (m.find()) {
				int count = Integer.parseInt(m.group(1));
				return (int) Math.ceil((double) count / 20.0);
			}
		} catch (Exception e) {
			logger.error(e);
		}
		return 1;
	}

	/**
	 * 从URL获取视频ID
	 * 
	 * @param url
	 * @return
	 */
	private String getVedioID(String url) {
		return url.substring(url.lastIndexOf('_') + 1, url.lastIndexOf('.'));
	}

	public static void main(String[] args) {
		String url = "http://www.56.com/u63/v_NTc0NzUzMTY.html";
		String[] a = new FiveSixCommentAlgo().extractor(new CrawlUrl(null, url));
		for (String s : a) {
			System.out.println(s);
		}

	}
}
